<script setup>
import { ref, onMounted, computed } from 'vue'
import { marked } from 'marked'
import { useUserStore } from '../../stores/user'
import { ElMessage } from 'element-plus'
import { CircleClose } from '@element-plus/icons-vue'
import axios from 'axios'

const userStore = useUserStore()
const loading = ref(false)
const userInput = ref('')
const chatHistory = ref([])
const currentRequest = ref(null)
const loadingMessage = ref(null)



const renderMarkdown = (text) => {
  if (text) {
    return marked(text)
  }
  return ''
}

// 终止对话
const stopChat = () => {
  if (currentRequest.value) {
    currentRequest.value.cancel()
    currentRequest.value = null
    loading.value = false
    if (loadingMessage.value) {
      const index = chatHistory.value.indexOf(loadingMessage.value)
      if (index > -1) {
        chatHistory.value.splice(index, 1)
      }
      loadingMessage.value = null
    }
    ElMessage.info('已终止对话')
  }
}

// 发送消息
const sendMessage = async () => {
  if (userInput.value.trim() === '') return
  if (loading.value) return
  
  const question = userInput.value
  userInput.value = ''
  loading.value = true
  
  // 创建取消令牌
  const cancelTokenSource = axios.CancelToken.source()
  currentRequest.value = cancelTokenSource
  
  // 添加用户问题和加载提示
  loadingMessage.value = {
    question,
    answer: '正在思考中，请稍等...',
    timestamp: new Date().toISOString(),
    isLoading: true
  }
  chatHistory.value.push(loadingMessage.value)
  
  // 滚动到底部
  setTimeout(() => {
    const chatContainer = document.querySelector('.chat-messages')
    if (chatContainer) {
      chatContainer.scrollTop = chatContainer.scrollHeight
    }
  }, 100)
  
  try {
    // 调用后端API获取AI回复
    const response = await axios.post('/api/ai/chat', 
      { question },
      { cancelToken: cancelTokenSource.token }
    )
    
    // 更新加载消息为实际回复
    const index = chatHistory.value.indexOf(loadingMessage.value)
    if (index > -1) {
      chatHistory.value[index] = {
        question,
        answer: response.data.answer,
        timestamp: response.data.timestamp || new Date().toISOString()
      }
    }
    
  } catch (error) {
    console.error('获取AI回复失败:', error)
    if (!axios.isCancel(error)) {
      ElMessage.error(error.response?.data?.message || '获取回复失败，请重试')
      // 更新加载消息为错误提示
      const index = chatHistory.value.indexOf(loadingMessage.value)
      if (index > -1) {
        chatHistory.value[index] = {
          question,
          answer: '抱歉，服务暂时不可用，请稍后再试。',
          timestamp: new Date().toISOString()
        }
      }
    }
  } finally {
    currentRequest.value = null
    loadingMessage.value = null
    loading.value = false
  }
}

// 清空聊天历史
const clearChat = () => {
  ElMessage.success('聊天记录已清空')
  chatHistory.value = []
}

// 处理按键事件
const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 格式化时间
const formatTime = (timestamp) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
}

// 初始化欢迎消息
onMounted(() => {
  chatHistory.value.push({
    question: '',
    answer: `您好，${userStore.userInfo.name || '用户'}！我是企业员工管理系统的智能助手，有什么可以帮您的吗？`,
    timestamp: new Date().toISOString()
  })
})
</script>

<template>
  <div class="chat-page">
    <div class="page-title">智能助手</div>
    
    <el-card class="chat-container">
      <template #header>
        <div class="card-header">
          <span>AI助手对话</span>
          <el-button type="primary" size="small" plain @click="clearChat">
            <el-icon><Delete /></el-icon> 清空对话
          </el-button>
        </div>
      </template>
      
      <div class="chat-content">
        <div class="chat-messages" ref="chatContainer">
          <div v-for="(message, index) in chatHistory" :key="index" class="message-wrapper">
            <!-- AI回复 -->
            <div v-if="message.answer && !message.question" class="message ai-message">
              <div class="message-content" :class="{ loading: message.isLoading }">
                <div class="message-text" v-html="renderMarkdown(message.answer)"></div>
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              </div>
              <div class="avatar ai-avatar">
                <el-icon><Service /></el-icon>
              </div>
            </div>
            
            <!-- 用户问题和AI回复 -->
            <template v-if="message.question">
              <!-- 用户问题 -->
              <div class="message user-message">
                <div class="avatar user-avatar">
                  <el-icon><User /></el-icon>
                </div>
                <div class="message-content">
                  <div class="message-text">{{ message.question }}</div>
                  <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                </div>
              </div>
              
              <!-- AI回复 -->
              <div class="message ai-message">
                <div class="message-content">
                  <div class="message-text" v-html="renderMarkdown(message.answer)"></div>
                  <div class="message-time">{{ formatTime(message.timestamp) }}</div>
                </div>
                <div class="avatar ai-avatar">
                  <el-icon><Service /></el-icon>
                </div>
              </div>
            </template>
          </div>
        </div>
        
        <div class="input-area">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="2"
            placeholder="请输入您的问题..."
            resize="none"
            @keydown="handleKeyDown"
            @keyup.enter.exact="sendMessage"
          />
          <div class="button-group">
            <el-button 
              type="danger" 
              :disabled="!loading"
              @click="stopChat"
              width="100%"
              height="100%"
            >
            
              <el-icon><CircleClose /></el-icon> 停止
            </el-button>
            <el-button 
              type="primary" 
              :loading="loading" 
              @click="sendMessage"
            >
              <el-icon><Position /></el-icon> 发送
            </el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.chat-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 20px;
  box-sizing: border-box;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.chat-container :deep(.el-card__body) {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  min-height: 0;
}

.chat-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  min-height: 0;
  margin-bottom: 0;
}

.message-wrapper {
  margin-bottom: 20px;
  padding-right: 5px;
}

.message {
  display: flex;
  margin-bottom: 15px;
  align-items: flex-start;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.user-avatar {
  background-color: #409EFF;
  color: white;
  margin-left: 10px;
}

.ai-avatar {
  background-color: #67C23A;
  color: white;
  margin-right: 10px;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 10px;
  position: relative;
  word-break: break-word;
  overflow-wrap: break-word;
}

.user-message .message-content {
  background-color: #ecf5ff;
  border: 1px solid #d9ecff;
  text-align: right;
}

.ai-message .message-content {
  background-color: #f0f9eb;
  border: 1px solid #e1f3d8;
}

.message-text {
  word-break: break-word;
  line-height: 1.5;
  white-space: pre-wrap;
}

.message-text :deep(p) {
  margin: 0.5em 0;
}

.message-text :deep(pre) {
  margin: 0.5em 0;
  padding: 1em;
  background-color: #f8f9fa;
  border-radius: 4px;
  overflow-x: auto;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.input-area {
  display: flex;
  align-items: flex-end;
  padding: 20px;
  border-top: 1px solid #EBEEF5;
  background-color: white;
  position: sticky;
  bottom: 0;
  z-index: 1;
}

.input-area .el-input {
  margin-right: 10px;
}

.input-area .button-group {
  display: flex;
  gap: 10px;
}

.input-area .el-button {
  height: 50px;
  width: 80px;
}

.message-content.loading {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  font-style: italic;
}
</style>